import cTitle from "components/title";
import { scrollMixin } from "utils/mixin";
import indexGoods from "../sachertorteComm/indexGoodsItem";
import sarchHistory from "components/searchHistory";
export default {
  components: {
    cTitle,
    indexGoods,
    sarchHistory
  },
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      search: "",
      tabActive: 0,
      keyword: "",
      classifyName: "分类",
      getBrand: [],
      brandNum: 11,
      goodsList: [],
      query: {
        page: 1,
        city: ""
      },
      totalPage: 0,
      isLoadMore: true,
      brandId: "", //区别是全部还是其他分类
      categorys: [
        //分类信息
        {
          id: 0,
          name: "全部"
        }
      ],
      timer: "", //防抖时间
      categorysId: "", //分类ID
      brandsId: "", //品牌ID
      locationStatus: false,
      storageName: "sachertorte", // 蛋糕显示历史搜索记录
      showHistory:false,
      total_page:0,
      background_color:'#ffc11e'
    };
  },
  activated() {
    if (this.$route.query.id) {
      this.tabActive = Number(this.$route.query.id);
      this.categorysId = Number(this.$route.query.id);
      this.classifyName = this.$route.query.classifyName;
    }
    if (this.tabActive === 0) {
      this.brandId = 0;
      this.brandsId = this.$route.query.brandId || "";
    }
    this.query.page = 1;
    this.categorys =  [
      //分类信息
      {
        id: 0,
        name: "全部"
      }
    ];
    this.categorysList();
    if(this.$route.query.city) {
      this.query.city = this.$route.query.city;
    }
    this.fun
      .getLocation()
      .then(res => {
        console.log(res);
        this.locationStatus = true;
        if (!this.query.city) {
          this.query.city = res.city;
        }
        this.getBrandsData();
        this.goodsByList();
      })
      .catch(err => {
        console.log(err);
        this.getBrandsData();
        this.goodsByList();
        this.locationStatus = false;
      });
  },
  methods: {
    // 点击tag搜索
    serachTag(data) {
      console.log(data)
      this.keyword = data;
      this.searchChange();
    },
    searchBlur() {
      this.showHistory = false;
    },
    hidebox(){
      this.searchHistoryList = window.localStorage.getItem(this.storageName) ? JSON.parse(window.localStorage.getItem(this.storageName)) : [];
      if (this.searchHistoryList.length > 0) {
        this.showHistory = true;
      }
    },
    searchChange() {
      //搜索事件
      this.query.page = 1;
      // if(!this.keyword) return
      if (this.timer) clearTimeout(this.timer);
      // 添加搜索记录
      if (this.$refs.searchHistory) {
        this.$refs.searchHistory.appendKeywords(this.keyword);
      }
      this.timer = setTimeout(() => {
        this.debounce(this.goodsByList());
      }, 500);
    },
    debounce(fn, delay) {
      let last, deferTimer;
      return function(args) {
        let that = this;
        let _args = arguments;
        let now = +new Date();
        if (last && now < last + delay) {
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function() {
            last = now;
            fn.apply(that, _args);
          }, delay);
        } else {
          last = now;
          fn.apply(that, _args);
        }
      };
    },
    exhibitionOn() {
      //展开
      this.brandNum = this.getBrand.length;
    },
    packup() {
      //收起
      this.brandNum = 11;
    },
    brandClick(id) {
      this.brandsId = id;
      this.query.page = 1;
      this.goodsByList();
    },
    categorysChange(id, name) {
      console.log(id, name);
      this.brandId = id;
      this.query.page = 1;
      this.categorysId = id;
      this.tabActive = id;
      this.goodsByList();
    },
    getBrandsData() {
      let query = {
        city: this.query.city
      };
      $http.get("plugin.yz-supply-cake.frontend.goods.goods.getBrand", query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.getBrand = res;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    categorysList() {
      $http.get("plugin.yz-supply-cake.frontend.index.index.getCategorys", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let list = res;
            for (let i in list) {
              this.categorys.push({
                id: list[i].id,
                name: list[i].name,
                thumb: list[i].thumb,
                thumb_url: list[i].thumb_url
              });
            }
            let info_basic = JSON.parse(localStorage.getItem("yz_basic_info"));
            this.background_color = info_basic.theme_color;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    goodsByList() {
      let urlStr = "plugin.yz-supply-cake.frontend.goods.goods.getGoodsList";
      urlStr += `&page=${this.query.page}`;
      urlStr += `&city=${this.query.city}`;
      urlStr += `&search[brand_id]=${this.brandsId}`;
      urlStr += `&search[category]=${this.categorysId}`;
      urlStr += `&search[keyword]=${this.keyword}`;
      $http.get(urlStr, {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.isLoadMore = true;
            this.totalPage = res.last_page;
            if (!this.totalPage) {
              this.query.page = 0;
            }
            this.goodsList = res.data;
          } else {
            this.page = this.page - 1;
            this.isLoadMore = false;
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //获取更多数据
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.totalPage) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        let urlStr = "plugin.yz-supply-cake.frontend.goods.goods.getGoodsList";
        urlStr += `&page=${this.query.page}`;
        urlStr += `&city=${this.query.city}`;
        urlStr += `&search[brand_id]=${this.brandsId}`;
        urlStr += `&search[category]=${this.categorysId}`;
        urlStr += `&search[keyword]=${this.keyword}`;
        $http.get(urlStr, {}, "加载中").then(
          res => {
            this.isLoadMore = true;
            if (res.result === 1) {
              let myData = res.data.data;
              this.goodsList = [...this.goodsList, ...myData]; //数组拼接
            } else {
              this.query.page = this.query.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    }
  }
};
